// 显示状态消息
function showStatus(message, isError = false) {
    const statusElement = document.getElementById('status');
    statusElement.textContent = message;
    statusElement.className = 'status ' + (isError ? 'error' : 'success');
    statusElement.style.display = 'block';
    
    setTimeout(() => {
        statusElement.style.display = 'none';
    }, 3000);
}

// 更新预览图片
function updatePreview(dataUrl) {
    const previewImage = document.getElementById('preview-image');
    const noPreview = document.getElementById('no-preview');
    
    if (dataUrl) {
        previewImage.src = dataUrl;
        previewImage.style.display = 'block';
        noPreview.style.display = 'none';
    } else {
        previewImage.style.display = 'none';
        noPreview.style.display = 'block';
    }
}

// 监听来自 background script 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'capture-success') {
        updatePreview(message.dataUrl);
        showStatus(message.action === 'clipboard' ? 
            'Copied to clipboard!' : 
            'Saved to file!');
    } else if (message.type === 'capture-error') {
        showStatus(message.error, true);
    }
});

// 默认设置
const DEFAULT_SETTINGS = {
    imageFormat: 'png',
    jpegQuality: '0.85',
    filenameFormat: 'title_time',
    customFormat: '{title}_{time}_{platform}'
};

// 加载设置
async function loadSettings() {
    const result = await chrome.storage.sync.get('settings');
    return { ...DEFAULT_SETTINGS, ...result.settings };
}

// 保存设置
async function saveSettings(settings) {
    await chrome.storage.sync.set({ settings });
}

// 加载历史记录
async function loadHistory() {
    const result = await chrome.storage.local.get('history');
    return result.history || [];
}

// 保存历史记录
async function saveHistory(history) {
    await chrome.storage.local.set({ history });
}

// 添加历史记录
async function addToHistory(frameData) {
    const history = await loadHistory();
    
    // 压缩图片数据以减小存储大小
    const compressedDataUrl = await compressImage(frameData.dataUrl, 0.7);
    
    const newEntry = {
        dataUrl: compressedDataUrl,
        title: frameData.title,
        platform: frameData.platform,
        timestamp: new Date().toISOString()
    };
    
    history.unshift(newEntry);
    
    // 只保留最近10条记录，而不是20条
    if (history.length > 10) {
        history.pop();
    }
    
    await saveHistory(history);
    updateHistoryList();
}

// 清空历史记录
async function clearHistory() {
    await saveHistory([]);
    updateHistoryList();
}

// 更新历史记录列表
async function updateHistoryList() {
    const historyList = document.getElementById('historyList');
    const history = await loadHistory();

    if (history.length === 0) {
        historyList.innerHTML = '<div class="not-video-page">暂无历史记录</div>';
        return;
    }

    // 清空现有内容
    historyList.innerHTML = '';

    // 创建并添加历史记录项
    history.forEach((item, index) => {
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        historyItem.innerHTML = `
            <img class="history-thumbnail" src="${item.dataUrl}" alt="缩略图">
            <div class="history-info">
                <div class="history-title">${item.title || '未知标题'}</div>
                <div class="history-time">${formatDate(item.timestamp)}</div>
            </div>
            <div class="history-actions">
                <button class="history-button" data-action="copy" data-index="${index}">复制</button>
                <button class="history-button" data-action="save" data-index="${index}">保存</button>
            </div>
        `;
        historyList.appendChild(historyItem);
    });

    // 添加事件委托
    historyList.addEventListener('click', async (e) => {
        const button = e.target.closest('.history-button');
        if (!button) return;

        const action = button.dataset.action;
        const index = parseInt(button.dataset.index);
        
        if (action === 'copy') {
            await copyHistoryItem(index);
        } else if (action === 'save') {
            await saveHistoryItem(index);
        }
    });
}

// 压缩图片
async function compressImage(dataUrl, quality = 0.7) {
    return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // 如果图片太大，进行缩放
            let width = img.width;
            let height = img.height;
            const maxDimension = 800;
            
            if (width > maxDimension || height > maxDimension) {
                if (width > height) {
                    height = (height / width) * maxDimension;
                    width = maxDimension;
                } else {
                    width = (width / height) * maxDimension;
                    height = maxDimension;
                }
            }
            
            canvas.width = width;
            canvas.height = height;
            
            ctx.drawImage(img, 0, 0, width, height);
            resolve(canvas.toDataURL('image/jpeg', quality));
        };
        img.src = dataUrl;
    });
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 从历史记录复制图片
async function copyHistoryItem(index) {
    const history = await loadHistory();
    const item = history[index];
    if (!item) return;

    try {
        // 创建一个临时的 canvas 来处理图片
        const img = new Image();
        img.crossOrigin = 'anonymous';
        
        await new Promise((resolve, reject) => {
            img.onload = resolve;
            img.onerror = reject;
            img.src = item.dataUrl;
        });

        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);

        // 转换为 Blob
        const blob = await new Promise(resolve => {
            canvas.toBlob(resolve, 'image/png');
        });

        // 复制到剪贴板
        await navigator.clipboard.write([
            new ClipboardItem({
                'image/png': blob
            })
        ]);
        
        showToast('已复制到剪贴板');
    } catch (error) {
        console.error('Failed to copy:', error);
        showToast('复制失败', 'error');
    }
}

// 从历史记录保存图片
async function saveHistoryItem(index) {
    const history = await loadHistory();
    const item = history[index];
    if (!item) return;

    const settings = await loadSettings();
    const filename = generateFilename(item.title, settings);
    
    chrome.downloads.download({
        url: item.dataUrl,
        filename: filename
    });
}

// 生成文件名
function generateFilename(title, settings) {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const safeTitle = title.replace(/[\\/:*?"<>|]/g, '_').trim();
    
    if (settings.filenameFormat === 'custom') {
        return settings.customFormat
            .replace('{title}', safeTitle)
            .replace('{time}', timestamp)
            .replace('{platform}', platform) + '.' + settings.imageFormat;
    }

    switch (settings.filenameFormat) {
        case 'title_time':
            return `${safeTitle}_${timestamp}.${settings.imageFormat}`;
        case 'time_title':
            return `${timestamp}_${safeTitle}.${settings.imageFormat}`;
        case 'title':
            return `${safeTitle}.${settings.imageFormat}`;
        default:
            return `${safeTitle}_${timestamp}.${settings.imageFormat}`;
    }
}

// 显示提示消息
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 2000);
    }, 10);
}

// 检测操作系统类型
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;

// 更新快捷键显示
function updateShortcutDisplay() {
    const shortcutsContainer = document.querySelector('.shortcuts');
    const shortcutHTML = `
        <div class="shortcut-item">
            <div class="shortcut-keys">
                ${isMac ? 
                    `<span class="key">⌥</span>
                     <span class="key">S</span>` : 
                    `<span class="key">Alt</span>
                     <span class="key">S</span>`}
            </div>
            <div class="shortcut-desc">复制当前帧到剪贴板</div>
        </div>
        <div class="shortcut-item">
            <div class="shortcut-keys">
                ${isMac ? 
                    `<span class="key">⌥</span>
                     <span class="key">⇧</span>
                     <span class="key">S</span>` : 
                    `<span class="key">Alt</span>
                     <span class="key">Shift</span>
                     <span class="key">S</span>`}
            </div>
            <div class="shortcut-desc">保存当前帧到文件</div>
        </div>
    `;
    shortcutsContainer.innerHTML = shortcutHTML;
}

document.addEventListener('DOMContentLoaded', async () => {
    updateShortcutDisplay();
    const videoInfoElement = document.getElementById('videoInfo');

    try {
        // 获取当前标签页
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        
        if (!tab) {
            showNoVideoMessage();
            return;
        }

        // 检查是否在支持的视频网站上
        const isYoutube = tab.url.includes('youtube.com/watch');
        const isBilibili = tab.url.includes('bilibili.com/video');

        if (!isYoutube && !isBilibili) {
            showNoVideoMessage();
            return;
        }

        // 从页面获取视频信息
        try {
            const result = await chrome.tabs.sendMessage(tab.id, { action: 'getVideoInfo' });
            if (result && result.success) {
                showVideoInfo(result, tab.url);
            } else {
                showNoVideoMessage();
            }
        } catch (error) {
            console.error('Failed to get video info:', error);
            // 如果出错，可能是content script还没有加载，尝试注入
            await chrome.scripting.executeScript({
                target: { tabId: tab.id },
                files: ['content.js']
            });
            // 重试获取视频信息
            setTimeout(async () => {
                try {
                    const result = await chrome.tabs.sendMessage(tab.id, { action: 'getVideoInfo' });
                    if (result && result.success) {
                        showVideoInfo(result, tab.url);
                    } else {
                        showNoVideoMessage();
                    }
                } catch (retryError) {
                    console.error('Retry failed:', retryError);
                    showNoVideoMessage();
                }
            }, 500);
        }
    } catch (error) {
        console.error('Error:', error);
        showNoVideoMessage();
    }

    await initializeSettings();
    await updateHistoryList();
});

function showVideoInfo(response, pageUrl) {
    const videoInfoElement = document.getElementById('videoInfo');
    const videoInfo = response.data || response;
    
    const html = `
        <div class="video-info">
            <div class="video-title">${videoInfo.title || '未知标题'}</div>
            <div class="video-meta">
                <span>${formatTime(videoInfo.currentTime || 0)} / ${formatTime(videoInfo.duration || 0)}</span>
                <button class="copy-link" data-url="${pageUrl}">复制视频链接</button>
            </div>
            <div class="platform-info">
                ${videoInfo.platform || '视频平台'}
            </div>
        </div>
    `;
    
    videoInfoElement.innerHTML = html;

    // 添加复制链接按钮的点击事件
    const copyButton = videoInfoElement.querySelector('.copy-link');
    copyButton.addEventListener('click', async () => {
        try {
            await navigator.clipboard.writeText(pageUrl);
            copyButton.textContent = '已复制';
            setTimeout(() => {
                copyButton.textContent = '复制视频链接';
            }, 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
            copyButton.textContent = '复制失败';
            setTimeout(() => {
                copyButton.textContent = '复制视频链接';
            }, 2000);
        }
    });
}

function showNoVideoMessage() {
    const videoInfoElement = document.getElementById('videoInfo');
    videoInfoElement.innerHTML = `
        <div class="not-video-page">
            请打开 YouTube 或 Bilibili 视频页面
        </div>
    `;
}

function formatTime(seconds) {
    if (!seconds) return '0:00';
    
    const pad = (num) => String(num).padStart(2, '0');
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    
    if (hours > 0) {
        return `${hours}:${pad(minutes)}:${pad(secs)}`;
    }
    return `${minutes}:${pad(secs)}`;
}

// 初始化设置界面
async function initializeSettings() {
    const settings = await loadSettings();
    
    const imageFormat = document.getElementById('imageFormat');
    const jpegQuality = document.getElementById('jpegQuality');
    const filenameFormat = document.getElementById('filenameFormat');
    const customFormat = document.getElementById('customFormat');
    const customFormatContainer = document.getElementById('customFormatContainer');

    imageFormat.value = settings.imageFormat;
    jpegQuality.value = settings.jpegQuality;
    filenameFormat.value = settings.filenameFormat;
    customFormat.value = settings.customFormat;

    // 根据图片格式启用/禁用JPEG质量选项
    jpegQuality.disabled = settings.imageFormat !== 'jpeg';

    // 根据文件名格式显示/隐藏自定义格式输入框
    customFormatContainer.style.display = 
        settings.filenameFormat === 'custom' ? 'block' : 'none';

    // 添加事件监听器
    imageFormat.addEventListener('change', async (e) => {
        const settings = await loadSettings();
        settings.imageFormat = e.target.value;
        jpegQuality.disabled = e.target.value !== 'jpeg';
        await saveSettings(settings);
    });

    jpegQuality.addEventListener('change', async (e) => {
        const settings = await loadSettings();
        settings.jpegQuality = e.target.value;
        await saveSettings(settings);
    });

    filenameFormat.addEventListener('change', async (e) => {
        const settings = await loadSettings();
        settings.filenameFormat = e.target.value;
        customFormatContainer.style.display = 
            e.target.value === 'custom' ? 'block' : 'none';
        await saveSettings(settings);
    });

    customFormat.addEventListener('change', async (e) => {
        const settings = await loadSettings();
        settings.customFormat = e.target.value;
        await saveSettings(settings);
    });

    // 添加清空历史记录按钮事件
    document.getElementById('clearHistory').addEventListener('click', clearHistory);
}
